<template>
  <div id="cesiumContainer">
    <!-- 摄像头列表侧边栏 -->
    <div
      class="camera-sidebar"
      :class="{ 'sidebar-collapsed': isSidebarCollapsed }"
    >
      <div class="sidebar-header">
        <h3>摄像头列表</h3>
        <button
          class="collapse-btn"
          @click="toggleSidebar"
          :title="isSidebarCollapsed ? '展开' : '折叠'"
        >
          {{ isSidebarCollapsed ? "›" : "‹" }}
        </button>
      </div>

      <div class="sidebar-content" v-if="!isSidebarCollapsed">
        <!-- 摄像头搜索 -->
        <div class="camera-search">
          <input
            v-model="searchQuery"
            placeholder="搜索摄像头..."
            type="text"
            class="search-input"
          />
        </div>

        <!-- 摄像头列表 -->
        <div class="camera-list">
          <div
            v-for="camera in filteredCameras"
            :key="camera.id"
            class="camera-item"
            draggable="true"
            @dragstart="onDragStart($event, camera)"
            @click="onCameraItemClick(camera)"
          >
            <div class="camera-icon">📹</div>
            <div class="camera-info">
              <div class="camera-name">{{ camera.name }}</div>
              <div class="camera-status" :class="camera.status">
                {{ getStatusText(camera.status) }} /
                {{ camera.placed ? "已放置" : "未放置" }}
              </div>
            </div>
            <button
              v-if="camera.placed"
              class="delete-btn"
              @click.stop="deleteCamera(camera)"
              title="删除摄像头"
            >
              ×
            </button>
          </div>
        </div>

        <!-- 添加新摄像头按钮 -->
        <div class="add-camera-section">
          <button class="add-camera-btn" @click="showAddCameraDialog = true">
            + 添加摄像头
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态指示器 -->
    <div
      v-if="loadingProgress > 0 && loadingProgress < 100"
      class="loading-indicator"
    >
      <div class="progress-bar">
        <div
          class="progress-fill"
          :style="{ width: loadingProgress + '%' }"
        ></div>
      </div>
      <div class="progress-text">
        加载建筑: {{ Math.round(loadingProgress) }}%
      </div>
    </div>

    <div
      v-if="buildingStatus"
      class="building-status"
      :class="buildingStatus.type"
    >
      {{ buildingStatus.message }}
    </div>

    <!-- 自定义Home按钮 -->
    <div
      class="custom-home-button"
      @click="flyToHungShuiKiu"
      title="定位到洪水桥"
    >
      <div class="home-icon">🏠</div>
    </div>

    <div
      class="custom-building-button"
      @click="toggleBuildings"
      :title="showBuildings ? '隐藏建筑物' : '显示建筑物'"
      :class="{ 'building-loading': buildingsLoading }"
    >
      <div class="building-icon">
        {{ buildingsLoading ? "⏳" : showBuildings ? "🏢" : "🏗️" }}
      </div>
      <span class="building-text">{{
        showBuildings ? "隐藏建筑" : "显示建筑"
      }}</span>
    </div>

    <!-- 添加摄像头对话框 -->
    <div v-if="showAddCameraDialog" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>添加新摄像头</h3>
          <button class="close-btn" @click="showAddCameraDialog = false">
            ×
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>摄像头名称:</label>
            <input v-model="newCamera.name" type="text" class="form-input" />
          </div>
          <div class="form-group">
            <label>描述:</label>
            <textarea
              v-model="newCamera.description"
              class="form-textarea"
            ></textarea>
          </div>
          <div class="form-group">
            <label>类型:</label>
            <select v-model="newCamera.type" class="form-select">
              <option value="surveillance">监控摄像头</option>
              <option value="traffic">交通摄像头</option>
              <option value="security">安防摄像头</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn-secondary" @click="showAddCameraDialog = false">
            取消
          </button>
          <button class="btn-primary" @click="addNewCamera">确认添加</button>
        </div>
      </div>
    </div>

    <!-- 摄像头详情面板 -->
    <div class="camera-detail-panel" v-if="selectedCamera">
      <div class="detail-header">
        <h4>摄像头详情</h4>
        <button class="close-btn" @click="selectedCamera = null">×</button>
      </div>
      <div class="detail-content">
        <div class="detail-item">
          <label>名称:</label>
          <span>{{ selectedCamera.name }}</span>
        </div>
        <div class="detail-item">
          <label>描述:</label>
          <span>{{ selectedCamera.description }}</span>
        </div>
        <div class="detail-item">
          <label>类型:</label>
          <span>{{ getCameraTypeText(selectedCamera.type) }}</span>
        </div>
        <div class="detail-item">
          <label>状态:</label>
          <span :class="['status-badge', selectedCamera.status]">
            {{ getStatusText(selectedCamera.status) }}
          </span>
        </div>
        <div class="detail-item">
          <label>坐标:</label>
          <span v-if="selectedCamera.position">
            经度: {{ selectedCamera.position[0].toFixed(6) }}<br />
            纬度: {{ selectedCamera.position[1].toFixed(6) }}<br />
            高度: {{ Math.round(selectedCamera.position[2]) }}米
          </span>
        </div>
        <!-- 添加高度控制 -->
        <div class="detail-item" v-if="selectedCamera.position">
          <label>高度调整:</label>
          <div class="height-controls">
            <button
              class="height-btn"
              @click="adjustCameraHeight(selectedCamera, -10)"
              title="降低10米"
            >
              -10m
            </button>
            <button
              class="height-btn"
              @click="adjustCameraHeight(selectedCamera, 10)"
              title="升高10米"
            >
              +10m
            </button>
          </div>
        </div>
        <div class="detail-actions">
          <button class="btn-secondary" @click="flyToCamera(selectedCamera)">
            定位
          </button>
          <button class="btn-danger" @click="deleteCamera(selectedCamera)">
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 绘制多边形控件 -->
    <div class="polygon-controls">
      <button
        class="polygon-btn"
        @click="startDrawingPolygon"
        title="绘制多边形区域"
      >
        📐 绘制区域
      </button>
      <button
        v-if="isDrawing"
        class="polygon-btn cancel"
        @click="cancelDrawing"
        title="取消绘制"
      >
        ❌ 取消
      </button>
    </div>

    <!-- 多边形编辑面板 -->
    <div class="polygon-edit-panel" v-if="selectedPolygon">
      <div class="detail-header">
        <h4>区域编辑</h4>
        <button class="close-btn" @click="closePolygonEdit">×</button>
      </div>
      <div class="detail-content">
        <div class="detail-item">
          <label>区域名称:</label>
          <input v-model="editingPolygon.name" type="text" class="form-input" />
        </div>
        <div class="detail-item">
          <label>边框颜色:</label>
          <input
            v-model="editingPolygon.outlineColor"
            type="color"
            class="color-input"
          />
        </div>
        <div class="detail-item">
          <label>边框宽度:</label>
          <div class="height-controls">
            <input
              v-model="editingPolygon.outlineWidth"
              type="number"
              class="height-input"
              min="1"
              max="10"
            />
            <span class="unit">像素</span>
          </div>
        </div>
        <div class="detail-item">
          <label>填充颜色:</label>
          <input
            v-model="editingPolygon.color"
            type="color"
            class="color-input"
          />
        </div>
        <div class="detail-item">
          <label>填充透明度:</label>
          <div class="opacity-controls">
            <input
              v-model="editingPolygon.fillOpacity"
              type="range"
              min="0"
              max="1"
              step="0.1"
              class="opacity-slider"
            />
            <span class="opacity-value"
              >{{ (editingPolygon.fillOpacity * 100).toFixed(0) }}%</span
            >
          </div>
        </div>
        <div class="detail-actions">
          <button class="btn-secondary" @click="flyToPolygon(selectedPolygon)">
            定位
          </button>
          <button class="btn-primary" @click="applyPolygonChanges">确定</button>
          <button class="btn-danger" @click="deletePolygon(selectedPolygon)">
            删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";

// 香港中心坐标和虚拟数据
const HONG_KONG_CENTER = [114.1694, 22.3193];
const HUNG_SHUI_KIU = [114.0024, 22.431];

// 香港边界范围
const HONG_KONG_BOUNDS = Cesium.Rectangle.fromDegrees(113.8, 22.1, 114.5, 22.6);

// 摄像头类型配置
const CAMERA_TYPES = {
  monitor: { name: "监控摄像头", color: Cesium.Color.GREEN },
  car: { name: "车辆防碰撞摄像头", color: Cesium.Color.BLUE },
  person: { name: "个人定位", color: Cesium.Color.RED },
  station: { name: "基站", color: Cesium.Color.YELLOW },
  lock: { name: "智能锁", color: Cesium.Color.RED },
  aiCam: { name: "AI摄像头", color: Cesium.Color.RED },
};

// 预定义摄像头列表
const PREDEFINED_CAMERAS = [
  {
    id: "cam-1",
    name: "海港监控点",
    description: "维多利亚港海景监控",
    type: "monitor",
    status: "online",
  },
  {
    id: "cam-2",
    name: "交通要道监控",
    description: "主要交通路口监控",
    type: "car",
    status: "online",
  },
  {
    id: "cam-3",
    name: "商业区安防",
    description: "商业中心安防监控",
    type: "person",
    status: "offline",
  },
  {
    id: "cam-4",
    name: "住宅区监控",
    description: "住宅区域安全监控",
    type: "station",
    status: "online",
  },
  {
    id: "cam-5",
    name: "高速公路监控",
    description: "高速公路交通监控",
    type: "lock",
    status: "online",
  },
];

export default {
  name: "CesiumMap",
  data() {
    return {
      loadingProgress: 0,
      buildingStatus: null,
      loadTimeout: null,
      cameraMinHeight: 50,
      cameraMaxHeight: 5000,
      animationFrameIds: new Set(),

      // 摄像头相关数据
      isSidebarCollapsed: false,
      searchQuery: "",
      cameras: JSON.parse(JSON.stringify(PREDEFINED_CAMERAS)),
      selectedCamera: null,
      showAddCameraDialog: false,
      newCamera: {
        name: "",
        description: "",
        type: "surveillance",
      },
      draggingCamera: null,
      dragHandler: null,

      // 多边形绘制相关数据 - 基于测量工具代码修改
      isDrawing: false,
      drawingHandler: null,
      tempPositions: [],
      polygons: [],
      selectedPolygon: null,
      editingPolygon: null,

      // 绘制实体
      drawingEntities: [],
      dynamicLineEntity: null,
      previewPolygonEntity: null,
      currentMousePosition: null,
      drawingHint: null,
      tempMessage: null,
      keyHandler: null,

      // 多边形默认样式 - 移除高度相关属性
      defaultPolygonStyle: {
        name: "未命名区域",
        color: "#00FF00",
        outlineColor: "#FFFFFF",
        fillOpacity: 0.3,
        outlineWidth: 2,
      },
      tempEntities: new Cesium.EntityCollection(),

      // 添加建筑物相关数据
      showBuildings: false,
      // buildingsTileset: null,
      buildingsLoading: false,
    };
  },
  computed: {
    filteredCameras() {
      if (!this.searchQuery) {
        return this.cameras;
      }
      const query = this.searchQuery.toLowerCase();
      return this.cameras.filter(
        (camera) =>
          camera.name.toLowerCase().includes(query) ||
          camera.description.toLowerCase().includes(query)
      );
    },
  },
  mounted() {
    this.initCesium();
    this.setupPerformanceMonitoring();
  },
  beforeDestroy() {
    this.destroyCesium();
  },
  methods: {
    // 性能监控方法
    setupPerformanceMonitoring() {
      // 监控帧率
      let frameCount = 0;
      let lastTime = performance.now();

      const monitorFrameRate = () => {
        frameCount++;
        const currentTime = performance.now();
        if (currentTime - lastTime >= 1000) {
          const fps = Math.round(
            (frameCount * 1000) / (currentTime - lastTime)
          );
          frameCount = 0;
          lastTime = currentTime;

          // 只在开发模式下显示FPS
          if (process.env.NODE_ENV === "development" && fps < 30) {
            console.warn(`低帧率警告: ${fps} FPS`);
          }
        }
        requestAnimationFrame(monitorFrameRate);
      };
      monitorFrameRate();
    },
    async initCesium() {
      try {
        const basemapProvider = new Cesium.UrlTemplateImageryProvider({
          url: "https://mapapi.geodata.gov.hk/gs/api/v1.0.0/xyz/imagery/WGS84/{z}/{x}/{y}.png",
          credit: "© Map from Lands Department",
          rectangle: HONG_KONG_BOUNDS,
          enablePickFeatures: false,
          maximumLevel: 16,
        });

        this.viewer = new Cesium.Viewer("cesiumContainer", {
          baseLayer: new Cesium.ImageryLayer(basemapProvider),
          baseLayerPicker: false,
          timeline: false,
          animation: false,
          vrButton: false,
          fullscreenButton: true,
          homeButton: false,
          navigationHelpButton: false,
          geocoder: true,
          sceneModePicker: false,
          requestRenderMode: true,
          maximumRenderTimeChange: Infinity,
          terrainProvider: undefined,
          shadows: false,
        });

        this.setupPerformanceOptimization();
        this.setInitialView();
        this.setupDragAndDrop();

        // 初始化多边形点击事件
        this.polygonClickHandler = this.setupPolygonClickHandler();

        // 延迟加载3D建筑数据
        setTimeout(() => {
          // this.loadHongKongBuildings();
        }, 1500);
      } catch (error) {
        console.error("初始化Cesium失败:", error);
        this.showBuildingStatus("地图初始化失败", "error");
      }
    },

    // 切换建筑物显示/隐藏
    async toggleBuildings() {
      if (this.buildingsLoading) return;

      this.showBuildings = !this.showBuildings;

      if (this.showBuildings && !this.buildingsTileset) {
        await this.loadBuildings();
      } else if (this.buildingsTileset) {
        this.buildingsTileset.show = this.showBuildings;

        // 如果建筑物已隐藏但瓦片未完全加载，重新显示时检查加载状态
        if (this.showBuildings && !this.buildingsTileset.allTilesLoaded) {
          this.buildingsLoading = true;
          this.showBuildingStatus("建筑物数据恢复加载...", "info");

          // 重新设置进度监控
          this.setupBuildingsLoadingProgress();
        }

        this.viewer.scene.requestRender();
      }
    },

    // 加载建筑物数据
    async loadBuildings() {
      try {
        this.buildingsLoading = true;
        this.showBuildingStatus("正在加载建筑物数据...", "info");

        const tilesetUrl =
          "https://data.map.gov.hk/api/3d-data/3dtiles/f2/tileset.json?key=3967f8f365694e0798af3e7678509421";

        console.log("开始加载建筑数据...");

        this.buildingsTileset = await Cesium.Cesium3DTileset.fromUrl(
          tilesetUrl,
          {
            maximumScreenSpaceError: 16,
            maximumNumberOfLoadedTiles: 100,
            skipLevelOfDetail: true,
            baseScreenSpaceError: 1024,
            skipScreenSpaceErrorFactor: 16,
            dynamicScreenSpaceError: true,
            dynamicScreenSpaceErrorDensity: 0.0025,
            dynamicScreenSpaceErrorFactor: 4.0,
            cullWithChildrenBounds: true,
            cullRequestsWhileMoving: true,
            cullRequestsWhileMovingMultiplier: 60.0,
            immediatelyLoadDesiredLevelOfDetail: false,
            loadSiblings: false,
            rectangle: HONG_KONG_BOUNDS,
            maximumMemoryUsage: 256,
            modelMatrix: Cesium.Matrix4.IDENTITY,
            shadows: Cesium.ShadowMode.DISABLED,
            debugWireframe: false,
            debugBoundingVolume: false,
            debugShowBoundingVolume: false,
          }
        );

        this.viewer.scene.primitives.add(this.buildingsTileset);
        this.buildingsTileset.show = true;

        // 使用 loadProgress 监听加载进度
        this.setupBuildingsLoadingProgress();

        // 使用 allTilesLoaded 监听完全加载状态
        this.buildingsTileset.allTilesLoaded.addEventListener(() => {
          console.log("所有建筑物瓦片已加载完成");
          this.buildingsLoading = false;
          this.showBuildingStatus("建筑物数据加载完成", "success");

          // 清除进度监听
          if (this.buildingsProgressHandler) {
            this.buildingsProgressHandler.destroy();
            this.buildingsProgressHandler = null;
          }
        });
      } catch (error) {
        this.buildingsLoading = false;
        this.showBuildings = false;
        this.showBuildingStatus(
          "建筑物数据加载失败: " + error.message,
          "error"
        );
        console.error("加载建筑物数据失败:", error);
      }
    },

    setupBuildingsLoadingProgress() {
      if (!this.buildingsTileset) return;

      let lastProgress = 0;
      const progressCheckInterval = 500; // 每500ms检查一次进度

      const checkProgress = () => {
        if (!this.buildingsTileset || this.buildingsTileset.allTilesLoaded) {
          return;
        }

        const currentProgress = this.buildingsTileset.loadProgress;

        // 只有当进度有显著变化时才更新状态
        if (Math.abs(currentProgress - lastProgress) > 0.1) {
          lastProgress = currentProgress;

          // 计算加载百分比（基于经验值调整）
          const progressPercent = Math.min(
            95,
            Math.round(currentProgress * 100)
          );

          if (progressPercent < 50) {
            this.showBuildingStatus(
              `正在初始化建筑物数据... ${progressPercent}%`,
              "info"
            );
          } else if (progressPercent < 80) {
            this.showBuildingStatus(
              `正在加载主要建筑... ${progressPercent}%`,
              "info"
            );
          } else {
            this.showBuildingStatus(
              `正在加载细节... ${progressPercent}%`,
              "info"
            );
          }

          console.log(`建筑物加载进度: ${progressPercent}%`);
        }

        // 如果还没完全加载，继续检查
        if (!this.buildingsTileset.allTilesLoaded) {
          setTimeout(checkProgress, progressCheckInterval);
        }
      };

      // 开始监控进度
      setTimeout(checkProgress, progressCheckInterval);
    },

    setupPerformanceOptimization() {
      const scene = this.viewer.scene;
      const cameraController = scene.screenSpaceCameraController;

      scene.requestRenderMode = false; // 改为false确保实时渲染
      scene.maximumRenderTimeChange = Infinity;

      // 添加性能优化但保持响应性
      scene.preRender.addEventListener(() => {
        // 强制在每次渲染前更新
        if (this.isDrawing) {
          scene.requestRender();
        }
      });

      cameraController.constrainedPitch = true;
      cameraController.minimumPitch = Cesium.Math.toRadians(-90);
      cameraController.maximumPitch = Cesium.Math.toRadians(-10);
      cameraController.autoResetHeadingPitch = false;
      cameraController.inertiaZoom = 0.7;
      cameraController.minimumZoomDistance = this.cameraMinHeight;
      cameraController.maximumZoomDistance = this.cameraMaxHeight;
      cameraController.enableCollisionDetection = true;

      scene.skyBox.show = false;
      scene.sun.show = false;
      scene.moon.show = false;
      scene.skyAtmosphere.show = false;
      scene.fog.enabled = false;

      scene.requestRenderMode = true;
      scene.maximumRenderTimeChange = Infinity;

      const pixelRatio = window.devicePixelRatio || 1;
      this.viewer.resolutionScale = Math.min(1.0, 1.5 / pixelRatio);

      scene.globe.showGroundAtmosphere = false;
      scene.globe.depthTestAgainstTerrain = false;
      this.viewer.targetFrameRate = 30;
    },

    setupDragAndDrop() {
      const cesiumContainer = document.getElementById("cesiumContainer");

      cesiumContainer.addEventListener("dragover", (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = "copy";
      });

      cesiumContainer.addEventListener("drop", (e) => {
        e.preventDefault();
        this.onMapDrop(e);
      });
    },

    onDragStart(event, camera) {
      event.dataTransfer.setData("text/plain", camera.id);
      this.draggingCamera = camera;
    },

    onMapDrop(event) {
      if (!this.draggingCamera) return;

      const rect = this.viewer.canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;

      const position = this.getPositionFromScreen(x, y);
      if (position) {
        const cartographic = Cesium.Cartographic.fromCartesian(position);
        const baseHeight = Math.max(cartographic.height, 50);
        const finalPosition = Cesium.Cartesian3.fromRadians(
          cartographic.longitude,
          cartographic.latitude,
          baseHeight + 30
        );

        this.placeCameraOnMap(this.draggingCamera, finalPosition);
      }

      this.draggingCamera = null;
    },

    getPositionFromScreen(x, y) {
      const scene = this.viewer.scene;
      const ray = scene.camera.getPickRay(new Cesium.Cartesian2(x, y));
      return scene.globe.pick(ray, scene);
    },

    placeCameraOnMap(camera, position) {
      this.removeCameraFromMap(camera);

      const cartographic = Cesium.Cartographic.fromCartesian(position);
      const longitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);
      const cameraHeight = Math.max(cartographic.height, 50) + 30;

      camera.position = [longitude, latitude, cameraHeight];
      camera.placed = true;

      const newPosition = Cesium.Cartesian3.fromDegrees(
        longitude,
        latitude,
        cameraHeight
      );

      const cameraType = CAMERA_TYPES[camera.type] || CAMERA_TYPES.monitor;

      const entity = this.viewer.entities.add({
        id: `camera-${camera.id}`,
        _cameraId: camera.id,
        name: camera.name,
        position: newPosition,
        billboard: {
          image: this.getCameraIcon(camera.type),
          scale: 1.5,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          heightReference: Cesium.HeightReference.NONE,
          color: cameraType.color,
          scaleByDistance: new Cesium.NearFarScalar(1.5e2, 2.0, 8.0e6, 0.8),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          translucencyByDistance: new Cesium.NearFarScalar(
            1.5e2,
            1.0,
            8.0e6,
            1.0
          ),
        },
        description: this.getCameraDescription(camera),
      });

      camera.entity = entity;
    },

    removeCameraFromMap(camera) {
      if (camera.entity) {
        this.viewer.entities.remove(camera.entity);
      }
    },

    adjustCameraHeight(camera, heightOffset = 0) {
      if (!camera.position || !camera.entity) return;

      const newHeight = camera.position[2] + heightOffset;
      camera.position[2] = newHeight;

      const newPosition = Cesium.Cartesian3.fromDegrees(
        camera.position[0],
        camera.position[1],
        newHeight
      );

      camera.entity.position = newPosition;

      console.log(`摄像头 ${camera.name} 高度调整为: ${newHeight}米`);
    },

    getCameraIcon(type) {
      const icons = {
        monitor: "/images/camera-icons/monitor.svg",
        car: "/images/camera-icons/car.svg",
        person: "/images/camera-icons/person.svg",
        station: "/images/camera-icons/station.svg",
        lock: "/images/camera-icons/lock.svg",
        aiCam: "/images/camera-icons/aiCam.svg",
      };

      return icons[type] || Cesium.buildModuleUrl("Widgets/Images/Camera.png");
    },

    getCameraDescription(camera) {
      return `
        <div class="camera-popup">
          <h3>${camera.name}</h3>
          <p><strong>描述:</strong> ${camera.description}</p>
          <p><strong>类型:</strong> ${this.getCameraTypeText(camera.type)}</p>
          <p><strong>状态:</strong> ${this.getStatusText(camera.status)}</p>
          <p><strong>坐标:</strong><br>
            经度: ${camera.position[0].toFixed(6)}<br>
            纬度: ${camera.position[1].toFixed(6)}<br>
            高度: ${Math.round(camera.position[2])}米
          </p>
        </div>
      `;
    },

    onCameraItemClick(camera) {
      if (camera.placed) {
        this.selectedCamera = camera;
      }
    },

    deleteCamera(camera) {
      if (confirm(`确定要删除摄像头 "${camera.name}" 吗？`)) {
        this.removeCameraFromMap(camera);

        camera.placed = false;
        delete camera.position;
        delete camera.entity;

        if (this.selectedCamera && this.selectedCamera.id === camera.id) {
          this.selectedCamera = null;
        }

        console.log(`摄像头 ${camera.name} 已删除`);
      }
    },

    flyToCamera(camera) {
      if (!camera.position) return;

      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          camera.position[0],
          camera.position[1],
          camera.position[2] + 100
        ),
        duration: 1.5,
        orientation: {
          heading: 0,
          pitch: -Cesium.Math.PI_OVER_TWO,
          roll: 0,
        },
      });
    },

    addNewCamera() {
      if (!this.newCamera.name.trim()) {
        alert("请输入摄像头名称");
        return;
      }

      const newCamera = {
        id: `cam-${Date.now()}`,
        name: this.newCamera.name,
        description: this.newCamera.description,
        type: this.newCamera.type,
        status: "online",
      };

      this.cameras.push(newCamera);

      this.newCamera = {
        name: "",
        description: "",
        type: "surveillance",
      };

      this.showAddCameraDialog = false;
    },

    toggleSidebar() {
      this.isSidebarCollapsed = !this.isSidebarCollapsed;
    },

    getStatusText(status) {
      const statusMap = {
        online: "在线",
        offline: "离线",
        error: "故障",
      };
      return statusMap[status] || "未知";
    },

    getCameraTypeText(type) {
      return CAMERA_TYPES[type]?.name || "未知类型";
    },

    setInitialView() {
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(114.1694, 22.3193, 3000),
        orientation: {
          heading: 0,
          pitch: -0.5,
          roll: 0,
        },
      });
    },

    flyToHungShuiKiu() {
      try {
        this.viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            HUNG_SHUI_KIU[0],
            HUNG_SHUI_KIU[1],
            2000
          ),
          orientation: {
            heading: 0,
            pitch: -Cesium.Math.PI_OVER_TWO,
            roll: 0,
          },
          duration: 2.0,
        });
      } catch (error) {
        console.error("定位到洪水桥失败:", error);
      }
    },

    // 基于测量工具的面积测量代码修改的多边形绘制方法
    startDrawingPolygon() {
      if (this.isDrawing) {
        this.cancelDrawing(); // 如果已经在绘制，先取消当前绘制
        return;
      }

      console.log("开始绘制多边形...");

      // 重置所有状态
      this.cleanupAllDrawingEntities();
      this.isDrawing = true;
      this.tempPositions = [];

      this.setupDrawingHandlers();
      this.showDrawingHint();

      console.log("绘制模式已启动，等待用户点击...");
    },

    // 单独设置绘制处理器
    setupDrawingHandlers() {
      if (this.drawingHandler) {
        this.drawingHandler.destroy();
      }

      this.drawingHandler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );

      // 左键点击添加点
      this.drawingHandler.setInputAction((event) => {
        if (!this.isDrawing) return;

        const position = this.getCatesian3FromPX(event.position);
        if (position && this.isValidPosition(position)) {
          this.addDrawingPoint(position);
          this.viewer.scene.requestRender();
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      // 优化鼠标移动更新 - 使用节流减少重绘频率
      let lastMoveTime = 0;
      const MOVE_UPDATE_INTERVAL = 32; // 约30fps

      this.drawingHandler.setInputAction((event) => {
        if (!this.isDrawing) return;

        const now = Date.now();
        if (now - lastMoveTime < MOVE_UPDATE_INTERVAL) return;
        lastMoveTime = now;

        const position = this.getCatesian3FromPX(event.endPosition);
        if (position && this.isValidPosition(position)) {
          this.currentMousePosition = position;
          this.updateDynamicEntities();
          // 移除这里的 requestRender，让系统自动管理渲染
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      // 右键完成绘制
      this.drawingHandler.setInputAction((event) => {
        if (!this.isDrawing) return;

        if (this.tempPositions.length >= 3) {
          this.finishDrawingPolygon();
        } else {
          this.showTempMessage("至少需要3个点来创建多边形，已自动取消绘制");
          // 自动取消绘制并清理所有内容
          setTimeout(() => {
            this.cancelDrawing();
          }, 1500); // 给用户时间看到提示消息
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      // ESC取消绘制
      this.keyHandler = (event) => {
        if (event.key === "Escape" && this.isDrawing) {
          this.cancelDrawing();
        }
      };
      document.addEventListener("keydown", this.keyHandler);
    },

    isValidPosition(position) {
      return (
        position &&
        position instanceof Cesium.Cartesian3 &&
        typeof position.clone === "function" &&
        !isNaN(position.x) &&
        !isNaN(position.y) &&
        !isNaN(position.z)
      );
    },

    updateDynamicEntities() {
      this.updateDynamicLine();
      this.updatePreviewPolygon();
    },

    getCatesian3FromPX(screenPosition) {
      try {
        const scene = this.viewer.scene;

        // 方法1: 直接使用globe.pick (最可靠)
        const ray = scene.camera.getPickRay(screenPosition);
        if (!ray) {
          console.warn("无法获取拾取射线");
          return null;
        }

        let position = scene.globe.pick(ray, scene);

        // 方法2: 如果方法1失败，使用椭球体pick
        if (!position) {
          position = scene.camera.pickEllipsoid(
            screenPosition,
            scene.globe.ellipsoid
          );
          if (position) {
            // 确保高度合理
            const cartographic = Cesium.Cartographic.fromCartesian(position);
            cartographic.height = Math.max(cartographic.height, 5);
            position = Cesium.Cartographic.toCartesian(cartographic);
          }
        }

        // 验证position是否是有效的Cartesian3
        if (!position || !position.x || !position.y || !position.z) {
          console.warn("获取的位置无效:", position);
          return null;
        }

        // 确保返回的是真正的Cartesian3实例
        if (!(position instanceof Cesium.Cartesian3)) {
          position = new Cesium.Cartesian3(position.x, position.y, position.z);
        }

        return position;
      } catch (error) {
        console.warn("获取位置失败:", error);
        return null;
      }
    },

    // 添加绘制点
    addDrawingPoint(position) {
      if (!this.isValidPosition(position)) {
        console.warn("无法添加无效的位置点:", position);
        return;
      }

      try {
        const clonedPosition = position.clone
          ? position.clone()
          : new Cesium.Cartesian3(position.x, position.y, position.z);

        this.tempPositions.push(clonedPosition);

        // 创建临时点实体，并标记为临时实体
        const pointEntity = this.viewer.entities.add({
          position: clonedPosition,
          point: {
            pixelSize: 10,
            color: Cesium.Color.YELLOW,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
          label: {
            text: `${this.tempPositions.length}`,
            font: "12pt sans-serif",
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            pixelOffset: new Cesium.Cartesian2(0, -20),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
          // 标记为临时实体，防止被点击
          _isDrawingEntity: true,
        });

        this.drawingEntities.push(pointEntity);
        console.log(`成功添加第 ${this.tempPositions.length} 个点`);
      } catch (error) {
        console.error("添加绘制点时出错:", error);
      }
    },

    updateDynamicLine() {
      // 如果没有鼠标位置或者没有固定点，则不显示动态线段
      if (!this.currentMousePosition || this.tempPositions.length === 0) {
        if (this.dynamicLineEntity) {
          this.viewer.entities.remove(this.dynamicLineEntity);
          this.dynamicLineEntity = null;
        }
        return;
      }

      const validPositions = this.tempPositions.filter((pos) =>
        this.isValidPosition(pos)
      );

      if (validPositions.length === 0) return;

      // 构建完整的线段路径：所有固定点 + 当前鼠标位置
      const positions = [...validPositions, this.currentMousePosition];

      if (!this.dynamicLineEntity) {
        this.dynamicLineEntity = this.viewer.entities.add({
          polyline: {
            positions: positions,
            width: 3,
            material: Cesium.Color.CYAN, // 使用实线替代虚线，提高性能
            // clampToGround: true,
          },
          // 标记为临时实体，防止被点击
          _isDrawingEntity: true,
        });
      } else {
        this.dynamicLineEntity.polyline.positions = positions;
      }
    },

    // 更新预览多边形
    updatePreviewPolygon() {
      if (this.tempPositions.length < 3 || !this.currentMousePosition) {
        if (this.previewPolygonEntity) {
          this.viewer.entities.remove(this.previewPolygonEntity);
          this.previewPolygonEntity = null;
        }
        return;
      }

      const closedPositions = [
        ...this.tempPositions,
        this.currentMousePosition,
        this.tempPositions[0],
      ];

      if (!this.previewPolygonEntity) {
        this.previewPolygonEntity = this.viewer.entities.add({
          polygon: {
            hierarchy: closedPositions,
            material: Cesium.Color.GREEN.withAlpha(0.3),
            outline: true,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2,
            clampToGround: true,
            // 添加性能优化选项
            classificationType: Cesium.ClassificationType.TERRAIN,
          },
          // 标记为临时实体，防止被点击
          _isDrawingEntity: true,
        });
      } else {
        // 只有在位置确实改变时才更新，避免不必要的重绘
        this.previewPolygonEntity.polygon.hierarchy = closedPositions;
      }
    },
    // 完成绘制
    finishDrawingPolygon() {
      if (this.tempPositions.length < 3) {
        this.showTempMessage("至少需要3个点来创建多边形");
        return;
      }

      try {
        // 首先清理所有临时实体（预览线、预览多边形等）
        this.cleanupTempEntities();

        // 创建正式的多边形实体
        const polygonId = "polygon-" + Date.now();
        const closedPositions = [...this.tempPositions, this.tempPositions[0]];

        const polygonEntity = this.viewer.entities.add({
          id: polygonId,
          name: this.defaultPolygonStyle.name,
          polygon: {
            hierarchy: new Cesium.PolygonHierarchy(closedPositions),
            material: Cesium.Color.fromCssColorString(
              this.defaultPolygonStyle.color
            ).withAlpha(this.defaultPolygonStyle.fillOpacity),
            outline: true,
            outlineColor: Cesium.Color.fromCssColorString(
              this.defaultPolygonStyle.outlineColor
            ),
            outlineWidth: this.defaultPolygonStyle.outlineWidth,
            // clampToGround: true,
            // classificationType: Cesium.ClassificationType.TERRAIN, // 性能优化
          },
          label: {
            text: this.defaultPolygonStyle.name,
            font: "14pt sans-serif",
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            pixelOffset: new Cesium.Cartesian2(0, 0),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
          },
        });

        // 保存多边形数据，包括点实体引用
        const polygonData = {
          id: polygonId,
          name: this.defaultPolygonStyle.name,
          positions: closedPositions.map((pos) => {
            const cartographic = Cesium.Cartographic.fromCartesian(pos);
            return {
              longitude: Cesium.Math.toDegrees(cartographic.longitude),
              latitude: Cesium.Math.toDegrees(cartographic.latitude),
              height: cartographic.height,
            };
          }),
          color: this.defaultPolygonStyle.color,
          outlineColor: this.defaultPolygonStyle.outlineColor,
          fillOpacity: this.defaultPolygonStyle.fillOpacity,
          outlineWidth: this.defaultPolygonStyle.outlineWidth,
          entity: polygonEntity,
          // 保存点实体引用，以便删除时清理
          pointEntities: [...this.drawingEntities],
        };

        this.polygons.push(polygonData);

        // 计算面积并设置描述
        const area = this.calculatePolygonArea(closedPositions);
        polygonEntity.description = this.getPolygonDescription(
          polygonData,
          area
        );

        // 注意：这里不清理绘制点实体，因为我们要保留它们作为多边形的标记点
        // 只清理临时实体（动态线和预览多边形）
        this.cleanupTempEntities();

        // 自动选中新创建的多边形
        this.selectedPolygon = polygonData;
        this.editingPolygon = { ...polygonData };

        console.log("多边形绘制完成:", polygonData);
        this.showTempMessage("多边形绘制完成！");
      } catch (error) {
        console.error("完成多边形绘制时出错:", error);
        this.showTempMessage("绘制失败，请重试", 5000);
        // 出错时也要清理所有内容
        this.cancelDrawing();
      } finally {
        // 清理绘制状态，但不清理点实体
        this.cleanupDrawingStateOnly();
      }
    },

    calculatePolygonArea(positions) {
      try {
        // 移除闭合点（最后一个点与第一个点相同）
        const polygonPositions = positions.slice(0, -1);

        // 使用Cesium的几何计算方法
        const polygon = new Cesium.PolygonGeometry({
          polygonHierarchy: new Cesium.PolygonHierarchy(polygonPositions),
          ellipsoid: this.viewer.scene.globe.ellipsoid,
        });

        const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
        if (geometry) {
          // 计算面积（平方米）
          return Cesium.Geometry.computeArea(geometry);
        }
        return 0;
      } catch (error) {
        console.warn("计算面积失败:", error);
        return 0;
      }
    },

    // 取消绘制
    cancelDrawing() {
      console.log("开始取消绘制，清理所有临时实体...");

      // 首先清理所有绘制相关的实体，包括点实体
      this.cleanupAllDrawingEntities();

      // 清理绘制状态
      this.isDrawing = false;
      this.tempPositions = [];
      this.currentMousePosition = null;

      // 清理事件监听器
      if (this.keyHandler) {
        document.removeEventListener("keydown", this.keyHandler);
        this.keyHandler = null;
      }

      if (this.drawingHandler && !this.drawingHandler.isDestroyed()) {
        this.drawingHandler.destroy();
        this.drawingHandler = null;
      }

      this.hideDrawingHint();

      // 确保场景重新渲染
      if (this.viewer && !this.viewer.isDestroyed) {
        this.viewer.scene.requestRender();
      }

      console.log("取消绘制完成，所有内容已清理");
      this.showTempMessage("已取消绘制");
    },

    // 清理绘制状态
    cleanupDrawing() {
      this.isDrawing = false;
      this.tempPositions = [];
      this.currentMousePosition = null;

      // 清理事件监听器
      if (this.keyHandler) {
        document.removeEventListener("keydown", this.keyHandler);
        this.keyHandler = null;
      }

      if (this.drawingHandler && !this.drawingHandler.isDestroyed()) {
        this.drawingHandler.destroy();
        this.drawingHandler = null;
      }

      // 清理所有绘制实体（包括点、线、预览多边形）
      this.cleanupAllDrawingEntities();
      this.hideDrawingHint();

      this.viewer.scene.requestRender();
    },

    cleanupAllDrawingEntities() {
      console.log("开始清理所有绘制实体...");

      const safelyRemoveEntity = (entity) => {
        if (entity && this.viewer && !this.viewer.isDestroyed) {
          try {
            this.viewer.entities.remove(entity);
          } catch (e) {
            console.warn("清理实体时出错:", e);
          }
        }
      };

      // 清理所有绘制点实体
      this.drawingEntities.forEach((entity) => {
        safelyRemoveEntity(entity);
      });
      this.drawingEntities = [];

      // 清理动态线和预览多边形
      safelyRemoveEntity(this.dynamicLineEntity);
      safelyRemoveEntity(this.previewPolygonEntity);

      this.dynamicLineEntity = null;
      this.previewPolygonEntity = null;

      // 强制重新渲染场景
      if (this.viewer && !this.viewer.isDestroyed) {
        this.viewer.scene.requestRender();
      }

      console.log("所有绘制实体清理完成");
    },

    cleanupDrawingEntities() {
      // 安全地清理所有实体
      const safelyRemoveEntity = (entity) => {
        if (entity && this.viewer && !this.viewer.isDestroyed) {
          try {
            this.viewer.entities.remove(entity);
          } catch (e) {
            console.warn("清理实体时出错:", e);
          }
        }
      };

      // 清理绘制实体
      this.drawingEntities.forEach((entity) => {
        safelyRemoveEntity(entity);
      });
      this.drawingEntities = [];

      // 清理动态实体
      safelyRemoveEntity(this.dynamicLineEntity);
      safelyRemoveEntity(this.previewPolygonEntity);

      this.dynamicLineEntity = null;
      this.previewPolygonEntity = null;
    },

    cleanupTempEntities() {
      // 清理动态线
      if (this.dynamicLineEntity) {
        try {
          this.viewer.entities.remove(this.dynamicLineEntity);
        } catch (e) {
          console.warn("清理动态线时出错:", e);
        }
        this.dynamicLineEntity = null;
      }

      // 清理预览多边形
      if (this.previewPolygonEntity) {
        try {
          this.viewer.entities.remove(this.previewPolygonEntity);
        } catch (e) {
          console.warn("清理预览多边形时出错:", e);
        }
        this.previewPolygonEntity = null;
      }

      this.currentMousePosition = null;

      // 请求重新渲染
      if (this.viewer && !this.viewer.isDestroyed) {
        this.viewer.scene.requestRender();
      }
    },

    cleanupDrawingStateOnly() {
      this.isDrawing = false;
      this.tempPositions = [];
      this.currentMousePosition = null;

      // 清理事件监听器
      if (this.keyHandler) {
        document.removeEventListener("keydown", this.keyHandler);
        this.keyHandler = null;
      }

      if (this.drawingHandler && !this.drawingHandler.isDestroyed()) {
        this.drawingHandler.destroy();
        this.drawingHandler = null;
      }

      this.cleanupTempEntities();
      this.hideDrawingHint();

      this.viewer.scene.requestRender();
    },

    // 清理绘制状态但保留点实体（用于完成绘制后的清理）
    cleanupDrawingStateKeepPoints() {
      this.isDrawing = false;
      this.currentMousePosition = null;

      // 清理事件监听器
      if (this.keyHandler) {
        document.removeEventListener("keydown", this.keyHandler);
        this.keyHandler = null;
      }

      if (this.drawingHandler && !this.drawingHandler.isDestroyed()) {
        this.drawingHandler.destroy();
        this.drawingHandler = null;
      }

      this.cleanupTempEntities();
      this.hideDrawingHint();

      if (this.viewer && !this.viewer.isDestroyed) {
        this.viewer.scene.requestRender();
      }
    },

    // 显示绘制提示
    showDrawingHint() {
      this.drawingHint = document.createElement("div");
      this.drawingHint.className = "drawing-hint";
      this.drawingHint.innerHTML = `
        <div class="hint-content">
          <h4>📐 绘制多边形区域</h4>
          <p>• 左键点击添加顶点</p>
          <p>• 右键点击自动闭合并完成</p>
          <p>• ESC键取消绘制</p>
          <p>• 至少需要3个顶点</p>
        </div>
      `;

      const container = this.viewer.container;
      container.appendChild(this.drawingHint);
    },

    // 隐藏绘制提示
    hideDrawingHint() {
      if (this.drawingHint && this.drawingHint.parentNode) {
        this.drawingHint.parentNode.removeChild(this.drawingHint);
        this.drawingHint = null;
      }
    },

    // 显示临时消息
    showTempMessage(message, duration = 3000) {
      if (this.tempMessage) {
        this.tempMessage.remove();
      }

      const messageEl = document.createElement("div");
      messageEl.className = "temp-message";
      messageEl.textContent = message;
      messageEl.style.cssText = `
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 12px 20px;
        border-radius: 6px;
        z-index: 10000;
        font-size: 14px;
        pointer-events: none;
      `;

      document.getElementById("cesiumContainer").appendChild(messageEl);
      this.tempMessage = messageEl;

      setTimeout(() => {
        if (messageEl.parentNode) {
          messageEl.parentNode.removeChild(messageEl);
        }
        if (this.tempMessage === messageEl) {
          this.tempMessage = null;
        }
      }, duration);
    },

    // 应用多边形修改
    applyPolygonChanges() {
      if (!this.selectedPolygon || !this.editingPolygon) return;

      try {
        // 更新多边形实体
        const polygon = this.selectedPolygon.entity.polygon;
        polygon.material = Cesium.Color.fromCssColorString(
          this.editingPolygon.color
        ).withAlpha(this.editingPolygon.fillOpacity);
        polygon.outlineColor = Cesium.Color.fromCssColorString(
          this.editingPolygon.outlineColor
        );
        polygon.outlineWidth = this.editingPolygon.outlineWidth;

        // 更新标签
        this.selectedPolygon.entity.label.text = this.editingPolygon.name;

        // 更新位置数据
        this.selectedPolygon.name = this.editingPolygon.name;
        this.selectedPolygon.color = this.editingPolygon.color;
        this.selectedPolygon.outlineColor = this.editingPolygon.outlineColor;
        this.selectedPolygon.fillOpacity = this.editingPolygon.fillOpacity;
        this.selectedPolygon.outlineWidth = this.editingPolygon.outlineWidth;

        // 更新描述信息
        this.selectedPolygon.entity.description = this.getPolygonDescription(
          this.selectedPolygon
        );

        console.log("多边形属性已更新:", this.selectedPolygon);
        this.showTempMessage("区域属性已更新！");

        // 关闭编辑面板
        this.closePolygonEdit();
      } catch (error) {
        console.error("更新多边形属性时出错:", error);
        this.showTempMessage("更新失败，请重试", 5000);
      }
    },

    // 关闭多边形编辑
    closePolygonEdit() {
      this.selectedPolygon = null;
      this.editingPolygon = null;
    },

    // 获取多边形描述信息
    getPolygonDescription(polygon, area = 0) {
      return `
        <div class="polygon-popup">
          <h3>${polygon.name}</h3>
          <p><strong>类型:</strong> 自定义区域</p>
          <p><strong>顶点数量:</strong> ${polygon.positions.length}</p>
          <p><strong>面积:</strong> ${area.toFixed(2)} 平方米</p>
          <p><strong>颜色:</strong> ${polygon.color}</p>
          <p>点击查看详情和编辑</p>
        </div>
      `;
    },

    // 定位到多边形
    flyToPolygon(polygon) {
      if (!polygon.entity) return;

      this.viewer.flyTo(polygon.entity, {
        duration: 1.5,
        offset: new Cesium.HeadingPitchRange(0, -0.5, 0),
      });
    },

    // 删除多边形
    deletePolygon(polygon) {
      if (confirm(`确定要删除区域 "${polygon.name}" 吗？`)) {
        // 删除多边形实体
        if (polygon.entity) {
          this.viewer.entities.remove(polygon.entity);
        }

        // 删除多边形对应的所有点实体
        if (polygon.pointEntities) {
          polygon.pointEntities.forEach((pointEntity) => {
            if (pointEntity && this.viewer.entities.contains(pointEntity)) {
              this.viewer.entities.remove(pointEntity);
            }
          });
        }

        // 从多边形数组中移除
        const index = this.polygons.findIndex((p) => p.id === polygon.id);
        if (index !== -1) {
          this.polygons.splice(index, 1);
        }

        // 清除选中状态
        if (this.selectedPolygon && this.selectedPolygon.id === polygon.id) {
          this.selectedPolygon = null;
          this.editingPolygon = null;
        }

        console.log("多边形和所有点已删除:", polygon.name);
        this.showTempMessage("区域已删除");
      }
    },

    // 设置多边形点击事件
    setupPolygonClickHandler() {
      const handler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );

      handler.setInputAction((event) => {
        if (this.isDrawing) return;

        const picked = this.viewer.scene.pick(event.position);
        if (Cesium.defined(picked) && picked.id) {
          const entity = picked.id;

          // 检查是否是临时实体或正式多边形实体
          if (entity._isDrawingEntity) {
            // 忽略临时实体（绘制过程中的实体）
            return;
          }

          if (entity.polygon) {
            const polygon = this.polygons.find((p) => p.entity === entity);
            if (polygon) {
              this.selectedPolygon = polygon;
              this.editingPolygon = { ...polygon };

              // 高亮选中的多边形
              this.highlightSelectedPolygon(polygon);

              // event.stopPropagation();
            }
          }
        } else {
          // 点击空白处取消选中
          this.clearPolygonHighlight();
          this.selectedPolygon = null;
          this.editingPolygon = null;
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      return handler;
    },

    // 优化多边形点击事件处理
    setupPolygonClickHandler() {
      const handler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );

      handler.setInputAction((event) => {
        if (this.isDrawing) return;

        const picked = this.viewer.scene.pick(event.position);
        if (Cesium.defined(picked) && picked.id) {
          const entity = picked.id;

          // 检查是否是多边形实体
          if (entity.polygon) {
            const polygon = this.polygons.find((p) => p.entity === entity);
            if (polygon) {
              this.selectedPolygon = polygon;
              this.editingPolygon = { ...polygon };

              // 高亮选中的多边形
              this.highlightSelectedPolygon(polygon);

              event.stopPropagation();
            }
          }
        } else {
          // 点击空白处取消选中
          this.clearPolygonHighlight();
          this.selectedPolygon = null;
          this.editingPolygon = null;
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      return handler;
    },

    // 新增高亮选中多边形方法
    highlightSelectedPolygon(polygon) {
      // 先清除之前的高亮
      this.clearPolygonHighlight();

      if (polygon.entity) {
        // 临时修改样式以示高亮
        const originalMaterial = polygon.entity.polygon.material;
        const originalOutlineWidth =
          polygon.entity.polygon.outlineWidth.getValue();

        polygon.entity.polygon.material = Cesium.Color.fromCssColorString(
          polygon.color
        ).withAlpha(0.5); // 增加透明度
        polygon.entity.polygon.outlineWidth = polygon.outlineWidth * 2; // 加粗边框

        // 存储原始样式以便恢复
        polygon._originalStyle = {
          material: originalMaterial,
          outlineWidth: originalOutlineWidth,
        };
      }
    },

    // 新增清除高亮方法
    clearPolygonHighlight() {
      this.polygons.forEach((polygon) => {
        if (polygon._originalStyle && polygon.entity) {
          polygon.entity.polygon.material = polygon._originalStyle.material;
          polygon.entity.polygon.outlineWidth =
            polygon._originalStyle.outlineWidth;
          delete polygon._originalStyle;
        }
      });
    },

    // 优化应用多边形修改方法
    applyPolygonChanges() {
      if (!this.selectedPolygon || !this.editingPolygon) return;

      try {
        const polygon = this.selectedPolygon.entity;

        // 更新多边形样式
        polygon.polygon.material = Cesium.Color.fromCssColorString(
          this.editingPolygon.color
        ).withAlpha(this.editingPolygon.fillOpacity);
        polygon.polygon.outlineColor = Cesium.Color.fromCssColorString(
          this.editingPolygon.outlineColor
        );
        polygon.polygon.outlineWidth = this.editingPolygon.outlineWidth;

        // 更新标签
        polygon.label.text = this.editingPolygon.name;

        // 更新数据
        Object.assign(this.selectedPolygon, {
          name: this.editingPolygon.name,
          color: this.editingPolygon.color,
          outlineColor: this.editingPolygon.outlineColor,
          fillOpacity: this.editingPolygon.fillOpacity,
          outlineWidth: this.editingPolygon.outlineWidth,
        });

        // 重新计算面积并更新描述
        const area = this.calculatePolygonArea(
          this.selectedPolygon.positions.map((pos) =>
            Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, 0)
          )
        );
        polygon.description = this.getPolygonDescription(
          this.selectedPolygon,
          area
        );

        console.log("多边形属性已更新:", this.selectedPolygon);
        this.showTempMessage("区域属性已更新！");

        // 重新应用高亮
        this.highlightSelectedPolygon(this.selectedPolygon);
      } catch (error) {
        console.error("更新多边形属性时出错:", error);
        this.showTempMessage("更新失败，请重试", 5000);
      }
    },

    async loadHongKongBuildings() {
      // 建筑加载代码保持不变
      try {
        const tilesetUrl =
          "https://data.map.gov.hk/api/3d-data/3dtiles/f2/tileset.json?key=3967f8f365694e0798af3e7678509421";

        console.log("开始加载建筑数据...");
        this.showBuildingStatus("开始加载建筑数据...", "info");
        this.loadingProgress = 10;

        this.tileset = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, {
          maximumScreenSpaceError: 16,
          maximumNumberOfLoadedTiles: 60,
          skipLevelOfDetail: true,
          baseScreenSpaceError: 1024,
          skipScreenSpaceErrorFactor: 16,
          dynamicScreenSpaceError: true,
          dynamicScreenSpaceErrorDensity: 0.0025,
          dynamicScreenSpaceErrorFactor: 4.0,
          cullWithChildrenBounds: true,
          cullRequestsWhileMoving: true,
          cullRequestsWhileMovingMultiplier: 60.0,
          immediatelyLoadDesiredLevelOfDetail: false,
          loadSiblings: false,
          rectangle: HONG_KONG_BOUNDS,
          maximumMemoryUsage: 128,
          modelMatrix: Cesium.Matrix4.IDENTITY,
          shadows: Cesium.ShadowMode.DISABLED,
          debugWireframe: false,
          debugBoundingVolume: false,
          debugShowBoundingVolume: false,
        });

        this.loadingProgress = 30;
        this.viewer.scene.primitives.add(this.tileset);
        this.setupTilesetLoadingProgress();

        this.loadTimeout = setTimeout(() => {
          if (this.loadingProgress < 100) {
            console.warn("建筑加载超时，强制完成");
            this.completeLoading("建筑加载超时，部分数据可能不完整", "warning");
          }
        }, 45000);
      } catch (error) {
        console.error("加载香港建筑数据失败:", error);
        this.completeLoading("建筑数据加载失败: " + error.message, "error");
      }
    },

    setupTilesetLoadingProgress() {
      // 进度监控代码保持不变
      if (!this.tileset) return;

      let lastProgressUpdate = 0;
      const progressCheckInterval = 500;
      let totalTilesLoaded = 0;
      const maxEstimatedTiles = 400;

      const updateProgress = () => {
        if (
          !this._checkViewerValid() ||
          !this.tileset ||
          this.loadingProgress >= 100
        ) {
          return;
        }

        const now = Date.now();
        if (now - lastProgressUpdate < progressCheckInterval) {
          const animationId = requestAnimationFrame(updateProgress);
          this.animationFrameIds.add(animationId);
          return;
        }

        lastProgressUpdate = now;

        try {
          const statistics = this.tileset._statistics;
          if (statistics) {
            const visited = statistics.visited || 0;
            const loaded = statistics.numberOfTilesWithContentReady || 0;

            if (loaded > totalTilesLoaded) {
              totalTilesLoaded = loaded;
            }

            const progress =
              30 + Math.min(65, (totalTilesLoaded / maxEstimatedTiles) * 65);
            this.loadingProgress = Math.max(this.loadingProgress, progress);

            if (loaded > 50 && progress > 80) {
              this.loadingProgress = 95;
              this.showBuildingStatus("建筑数据基本加载完成", "success");
              this.completeLoading("建筑数据加载完成", "success");
              return;
            }

            if (totalTilesLoaded % 30 === 0) {
              this.showBuildingStatus(
                `已加载 ${totalTilesLoaded} 个建筑瓦片`,
                "info"
              );
            }
          }
        } catch (error) {
          console.warn("进度更新出错:", error);
        }

        const animationId = requestAnimationFrame(updateProgress);
        this.animationFrameIds.add(animationId);
      };

      updateProgress();
    },

    completeLoading(message = "建筑数据加载完成", type = "success") {
      if (this.loadTimeout) {
        clearTimeout(this.loadTimeout);
        this.loadTimeout = null;
      }

      this.loadingProgress = 100;
      console.log(message);
      this.showBuildingStatus(message, type);

      setTimeout(() => {
        this.loadingProgress = 0;
        setTimeout(() => {
          this.buildingStatus = null;
        }, 3000);
      }, 2000);
    },

    showBuildingStatus(message, type = "info") {
      this.buildingStatus = {
        message,
        type,
      };
    },

    destroyCesium() {
      // 清理建筑物相关的监听器
      if (this.buildingsProgressHandler) {
        this.buildingsProgressHandler.destroy();
        this.buildingsProgressHandler = null;
      }

      this.animationFrameIds.forEach((id) => {
        cancelAnimationFrame(id);
      });
      this.animationFrameIds.clear();

      if (this.dragHandler && !this.dragHandler.isDestroyed()) {
        this.dragHandler.destroy();
      }

      if (this.polygonClickHandler) {
        this.polygonClickHandler.destroy();
      }

      if (this.buildingsTileset) {
        try {
          this.viewer.scene.primitives.remove(this.buildingsTileset);
          this.buildingsTileset = null;
        } catch (error) {
          console.warn("移除建筑物tileset时出错:", error);
        }
      }

      this.cleanupDrawing();

      this.polygons.forEach((polygon) => {
        if (polygon.entity) {
          try {
            this.viewer.entities.remove(polygon.entity);
          } catch (e) {
            console.warn("清理多边形实体时出错:", e);
          }
        }
      });
      this.polygons = [];

      if (!this.viewer) return;

      try {
        console.log("开始清理Cesium资源...");

        if (this.loadTimeout) {
          clearTimeout(this.loadTimeout);
          this.loadTimeout = null;
        }

        this.cameras.forEach((camera) => {
          this.removeCameraFromMap(camera);
        });

        this.viewer.entities.removeAll();

        if (this.tileset) {
          try {
            this.viewer.scene.primitives.remove(this.tileset);
            this.tileset = null;
          } catch (error) {
            console.warn("移除tileset时出错:", error);
          }
        }

        this.viewer.imageryLayers.removeAll();
        this.viewer.dataSources.removeAll();

        this.viewer.destroy();
        this.viewer = null;

        console.log("Cesium资源已销毁");
      } catch (error) {
        console.error("销毁Cesium时出错:", error);
      }
    },

    _checkViewerValid() {
      return this.viewer && !this.viewer.isDestroyed;
    },
  },

  beforeCreate() {
    this.viewer = null;
    this.tileset = null;
  },
};
</script>

<style scoped>
/* 原有的CSS样式保持不变，只添加新的样式 */

/* 透明度控制样式 */
.opacity-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.opacity-slider {
  flex: 1;
}

.opacity-value {
  color: #ccc;
  font-size: 12px;
  min-width: 40px;
}

/* 其他样式保持不变 */
#cesiumContainer {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: relative;
}

.camera-sidebar {
  position: absolute;
  left: 0;
  top: 0;
  width: 320px;
  height: 100%;
  background: rgba(30, 30, 35, 0.95);
  backdrop-filter: blur(10px);
  border-right: 1px solid #444;
  z-index: 1000;
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
}

.camera-sidebar.sidebar-collapsed {
  transform: translateX(-280px);
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #444;
  background: rgba(40, 40, 45, 0.9);
}

.sidebar-header h3 {
  margin: 0;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
}

.collapse-btn {
  background: none;
  border: 1px solid #666;
  color: #fff;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.collapse-btn:hover {
  background: #555;
}

.sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.camera-search {
  padding: 16px 20px;
  border-bottom: 1px solid #444;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid #555;
  border-radius: 6px;
  color: #fff;
  font-size: 14px;
}

.search-input::placeholder {
  color: #999;
}

.search-input:focus {
  outline: none;
  border-color: #007acc;
}

.camera-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.camera-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #333;
  cursor: grab;
  transition: background-color 0.2s ease;
  position: relative;
}

.camera-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.camera-item:active {
  cursor: grabbing;
}

.camera-icon {
  font-size: 20px;
  margin-right: 12px;
  flex-shrink: 0;
}

.camera-info {
  flex: 1;
  min-width: 0;
}

.camera-name {
  color: #fff;
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.camera-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

.camera-status.online {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

.camera-status.offline {
  background: rgba(158, 158, 158, 0.2);
  color: #9e9e9e;
}

.camera-status.error {
  background: rgba(244, 67, 54, 0.2);
  color: #f44336;
}

.delete-btn {
  background: rgba(244, 67, 54, 0.2);
  border: none;
  color: #f44336;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.camera-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  background: rgba(244, 67, 54, 0.4);
}

.add-camera-section {
  padding: 16px 20px;
  border-top: 1px solid #444;
}

.add-camera-btn {
  width: 100%;
  padding: 10px;
  background: rgba(0, 122, 204, 0.3);
  border: 1px solid #007acc;
  color: #007acc;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
}

.add-camera-btn:hover {
  background: rgba(0, 122, 204, 0.4);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: #2d2d30;
  border-radius: 8px;
  width: 400px;
  max-width: 90vw;
  border: 1px solid #444;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #444;
}

.modal-header h3 {
  margin: 0;
  color: #fff;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #fff;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  color: #ccc;
  margin-bottom: 6px;
  font-size: 14px;
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid #555;
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #007acc;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #444;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn-primary,
.btn-secondary,
.btn-danger {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
}

.btn-primary {
  background: #007acc;
  color: #fff;
}

.btn-primary:hover {
  background: #005a9e;
}

.btn-secondary {
  background: #555;
  color: #fff;
}

.btn-secondary:hover {
  background: #666;
}

.btn-danger {
  background: #d32f2f;
  color: #fff;
}

.btn-danger:hover {
  background: #b71c1c;
}

.camera-detail-panel {
  position: absolute;
  right: 10px;
  top: 100px;
  width: 300px;
  background: rgba(30, 30, 35, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid #444;
  border-radius: 8px;
  z-index: 1000;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #444;
}

.detail-header h4 {
  margin: 0;
  color: #fff;
  font-size: 16px;
}

.detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 12px;
}

.detail-item label {
  display: block;
  color: #999;
  font-size: 12px;
  margin-bottom: 4px;
}

.detail-item span {
  color: #fff;
  font-size: 14px;
  line-height: 1.4;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-badge.online {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

.status-badge.offline {
  background: rgba(158, 158, 158, 0.2);
  color: #9e9e9e;
}

.detail-actions {
  display: flex;
  gap: 8px;
  margin-top: 20px;
}

.detail-actions button {
  flex: 1;
}

.loading-indicator {
  position: absolute;
  top: 10px;
  left: 340px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 12px 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 180px;
  backdrop-filter: blur(4px);
}

.progress-bar {
  width: 100%;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4caf50, #45a049);
  border-radius: 3px;
  transition: width 0.3s ease;
  box-shadow: 0 0 8px rgba(76, 175, 80, 0.3);
}

.progress-text {
  font-size: 13px;
  color: #333;
  text-align: center;
  font-weight: 500;
}

.building-status {
  position: absolute;
  top: 70px;
  right: 10px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 10px 14px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  font-size: 13px;
  max-width: 220px;
  transition: all 0.3s ease;
  backdrop-filter: blur(4px);
}

.building-status.info {
  border-left: 4px solid #2196f3;
  background: rgba(33, 150, 243, 0.05);
}

.building-status.success {
  border-left: 4px solid #4caf50;
  background: rgba(76, 175, 80, 0.05);
}

.building-status.warning {
  border-left: 4px solid #ff9800;
  background: rgba(255, 152, 0, 0.05);
}

.building-status.error {
  border-left: 4px solid #f44336;
  background: rgba(244, 67, 54, 0.05);
}

.custom-home-button {
  position: absolute;
  top: 10px;
  right: 270px;
  background: rgba(40, 40, 40, 0.7);
  padding: 8px 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  gap: 8px;
  border: 1px solid #444;
  border-radius: 6px;
}

.custom-home-button:hover {
  background: #48b;
  border-color: #ea4;
}

.home-icon {
  font-size: 16px;
}

.height-controls {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.height-btn {
  flex: 1;
  padding: 6px 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid #555;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s ease;
}

.height-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.camera-icon-large {
  font-size: 24px;
  filter: drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.5));
}

.polygon-controls {
  position: absolute;
  top: 10px;
  right: 140px;
  z-index: 1000;
  display: flex;
  gap: 8px;
}

.polygon-btn {
  background: rgba(40, 40, 40, 0.7);
  border: 1px solid #444;
  color: #fff;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 12px;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;
}

.polygon-btn:hover {
  background: rgba(0, 122, 204, 0.7);
  border-color: #007acc;
}

.polygon-btn.cancel {
  background: rgba(211, 47, 47, 0.7);
}

.polygon-btn.cancel:hover {
  background: rgba(183, 28, 28, 0.7);
}

.polygon-edit-panel {
  position: absolute;
  right: 10px;
  top: 150px;
  width: 300px;
  background: rgba(30, 30, 35, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid #444;
  border-radius: 8px;
  z-index: 1000;
}

.height-input {
  width: 80px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid #555;
  border-radius: 4px;
  color: #fff;
}

.unit {
  margin-left: 8px;
  color: #ccc;
}

.color-input {
  width: 60px;
  height: 30px;
  background: transparent;
  border: 1px solid #555;
  border-radius: 4px;
  cursor: pointer;
}

.polygon-popup {
  color: #333;
  max-width: 250px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.polygon-popup h3 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 2px solid #27ae60;
  padding-bottom: 6px;
  font-size: 16px;
}

.polygon-popup p {
  margin: 6px 0;
  line-height: 1.4;
  font-size: 14px;
}

.drawing-hint {
  position: absolute;
  top: 120px;
  right: 10px;
  background: rgba(30, 30, 35, 0.95);
  border: 1px solid #444;
  border-radius: 8px;
  padding: 16px;
  z-index: 1000;
  backdrop-filter: blur(10px);
  min-width: 200px;
}

.drawing-hint h4 {
  margin: 0 0 12px 0;
  color: #fff;
  font-size: 14px;
  border-bottom: 1px solid #444;
  padding-bottom: 8px;
}

.drawing-hint p {
  margin: 6px 0;
  color: #ccc;
  font-size: 12px;
  line-height: 1.4;
}

.temp-message {
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translate(-50%, -40%);
  }
  20% {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
  80% {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
  100% {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
}

.polygon-edit-panel {
  position: absolute;
  right: 10px;
  top: 120px;
  width: 300px;
  background: rgba(30, 30, 35, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid #444;
  border-radius: 8box;
  z-index: 1000;
  max-height: 80vh;
  overflow-y: auto;
}

.drawing-hint + .polygon-edit-panel {
  top: 280px;
}

/* 建筑物控制按钮样式 */
.custom-building-button {
  position: absolute;
  top: 10px;
  right: 380px;
  background: rgba(40, 40, 40, 0.7);
  padding: 8px 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  gap: 8px;
  border: 1px solid #444;
  border-radius: 6px;
  color: #fff;
  font-size: 12px;
}

.custom-building-button:hover {
  background: rgba(0, 122, 204, 0.7);
  border-color: #007acc;
}

.custom-building-button.building-loading {
  background: rgba(255, 152, 0, 0.7);
  cursor: not-allowed;
}

.building-icon {
  font-size: 16px;
}

.building-text {
  white-space: nowrap;
}
</style>

<style>
.camera-popup {
  color: #333;
  max-width: 250px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.camera-popup h3 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 6px;
  font-size: 16px;
}

.camera-popup p {
  margin: 6px 0;
  line-height: 1.4;
  font-size: 14px;
}

.cesium-widget-credits {
  display: none !important;
}

.cesium-widget-errorPanel {
  display: none !important;
}

.cesium-viewer-toolbar {
  opacity: 0.9;
  right: 54px;
}

.cesium-viewer-animationContainer {
  display: none;
}

.cesium-viewer-timelineContainer {
  display: none;
}

.cesium-home-button {
  display: none !important;
}

.camera-list::-webkit-scrollbar {
  width: 6px;
}

.camera-list::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
}

.camera-list::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.camera-list::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>
